package cn.jiaqiang.chatgpt.data.domain.openai.service.chat.userType;

import cn.jiaqiang.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.RuleLogicEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.LogicCheckTypeVO;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.impl.ChatGLMService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.impl.ChatGPTService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.chat.IUserTypeGroupService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.chat.UserChatService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

/**
 * User: jia-qiang
 * Date: 2024-04-04
 * Time: 21:33
 */
@Slf4j
@Component
public class WhiteUserUserChatService extends UserChatService implements IUserTypeGroupService {

    public WhiteUserUserChatService(ChatGPTService chatGPTService, ChatGLMService chatGLMService) {
        super(chatGPTService, chatGLMService);
    }

    @Override
    public boolean chat(ChatProcessAggregate chatProcess, UserAccountEntity userAccountEntity,
                     ResponseBodyEmitter emitter) throws Exception {

        log.info("白名单用户: {} 不做拦截", userAccountEntity.getUserId());
        RuleLogicEntity<ChatProcessAggregate> ruleLogic = this.doCheckLogic(
                chatProcess, userAccountEntity
        );
        if (!LogicCheckTypeVO.SUCCESS.equals(ruleLogic.getType())) {
            emitter.send(ruleLogic.getInfo());
            emitter.complete();
            throw new RuntimeException("校验未通过.");
        }
        // 应答处理
        try {
            openAiGroup.get(chatProcess.getChannel()).doMessageResponse(ruleLogic.getData(), emitter);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("流式对话失败, ", e);
        }
    }

}
